package cn.com.longfuinfo.wx.interceptor;

import org.apache.log4j.Logger;

import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;

import cn.com.longfuinfo.wx.common.Constants;
import cn.com.longfuinfo.wx.controller.BaseController;
import cn.com.longfuinfo.wx.kit.CommonKit;
import cn.com.longfuinfo.wx.kit.MapKit;

/**
 * 拦截用户请求，判断如果是首次访问，则重定向至微信用户授权
 */
public class OAuthInterceptor extends AjaxInterceptor{
	private Logger logger = Logger.getLogger(getClass());
	
	@Override
	public void onAjax(Invocation inv) {
		BaseController c = (BaseController)inv.getController();
		//判断用户是否授权过
		if(c.getSessionAttr(Constants.WX_OAUTH)==null){
			String validcode = CommonKit.randomNum(6);
			logger.error("用户未进行过授权，准备跳转授权，验证码："+validcode);
			c.setSessionAttr(Constants.WX_OAUTH_VALIDCODE, validcode);
			c.renderResult(-3,MapKit.one().put("authUrl", SnsAccessTokenApi.getAuthorizeURL(ApiConfigKit.getApiConfig().getAppId(), CommonKit.encodeURL(PropKit.get("constants.url_prev")+"/oauth?backurl="+CommonKit.encodeURL("/index")), validcode, false)).getAttrs());
			return;
		}
		inv.invoke();
	}
	
	@Override
	public void onAjaxNope(Invocation inv) {
		BaseController c = (BaseController)inv.getController();
		//判断用户是否授权过
		if(c.getSessionAttr(Constants.WX_OAUTH)==null){
			//截取访问地址的后边action部分，跳转至微信授权，并传递过去
			String backurl = getRequestUrl(c);
			String validcode = CommonKit.randomNum(6);
			logger.error("~用户未进行过授权，准备跳转授权，验证码："+validcode);
			c.setSessionAttr(Constants.WX_OAUTH_VALIDCODE, validcode);
			c.redirect(SnsAccessTokenApi.getAuthorizeURL(ApiConfigKit.getApiConfig().getAppId(), CommonKit.encodeURL(PropKit.get("constants.url_prev")+"/oauth?backurl="+CommonKit.encodeURL(backurl)), validcode, false));
			return;
		}
		inv.invoke();
	}
	
	/**
	 * 从request中获取用户请求的地址及请求参数，如果为空，则返回/index
	 */
	private String getRequestUrl(BaseController c){
		String backurl = "/";
		//网站地址前缀
		String prevUrl = PropKit.get("constants.url_prev");
		//用户请求地址
		String requestUrl = c.getRequest().getRequestURL().toString();
		//用户请求参数
		String queryString = c.getRequest().getQueryString();
		//判断请求地址是本站地址
		if(!StrKit.isBlank(requestUrl)&&requestUrl.startsWith(prevUrl)){
			//截取访问地址的后边action部分，跳转至微信授权，并传递过去
			backurl = requestUrl.substring(prevUrl.length());
			if(!StrKit.isBlank(queryString)){
				backurl = backurl + "?" + queryString;
			}
		}
		if(backurl.equals("/")){
			backurl = "/index";
		}
		return backurl;
	}
}
